import dateIcon from "@/assets/images/public/new-date.png";
import { rem } from "@mantine/core";
import { type DatePickerProps, DatePickerInput, DateValue } from "@mantine/dates";
import "@mantine/dates/styles.css";
import classNames from "classnames";
import React from "react";

import { NImage } from "@/components/Uikit";
import { mergeClassNames } from "../tools";
import styles from "./DatePicker.module.less";

interface ExtendedDatePickerProps extends DatePickerProps {
  className?: string;
  value: any;
  onChange: (value: any) => void;
}
export const NDatePicker = React.memo(({ className, ...restProps }: ExtendedDatePickerProps) => {
  const selectStyle = {
    style: {
      background: "var(--mantine-color-btnBgColor-0)",
      borderRadius: rem(6),
      width: "100%",
    },
  };

  const isDateMatch = (
    compareDate: Date | DateValue | undefined,
    checkDate: Date,
    unit: "year" | "month" | "day",
  ) => {
    if (!compareDate) return false;
    switch (unit) {
      case "year":
        return compareDate.getFullYear() === checkDate.getFullYear();
      case "month":
        return (
          compareDate.getFullYear() === checkDate.getFullYear() &&
          compareDate.getMonth() === checkDate.getMonth()
        );
      case "day":
        return (
          compareDate.getFullYear() === checkDate.getFullYear() &&
          compareDate.getMonth() === checkDate.getMonth() &&
          compareDate.getDate() === checkDate.getDate()
        );
      default:
        return false;
    }
  };

  const controlProps = (type: "year" | "month" | "day", date: Date) => {
    if (restProps.type == "multiple" || restProps.type == "range") return {};
    const dateTypeMatch = isDateMatch(restProps.value, date, type);
    return dateTypeMatch ? selectStyle : {};
  };
  {
    return (
      <DatePickerInput
        className={classNames(className)}
        valueFormat='YYYY-MM-DD'
        allowSingleDateInRange={restProps.type == "range" ? true : false}
        classNames={mergeClassNames(styles, restProps.classNames)}
        rightSection={<NImage src={dateIcon} className='w-16 h-16' />}
        getDayProps={(date) => controlProps("day", date)}
        getMonthControlProps={(date) => controlProps("month", date)}
        getYearControlProps={(date) => controlProps("year", date)}
        {...restProps}
      />
    );
  }
});
